package com.lottery.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.lottery.dao.qiuqiu.accoutDao.UserDao;
import com.lottery.dao.qiuqiu.statisticsDao.AgencyDao;
import com.lottery.service.qiuqiu.JedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

//拦截器检验用户是否登录及登录异常
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JedisClient jedisClient;
    // 用户token的key
    @Value("${TOKEN}")
    private String TOKEN;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserDao userDao;

    @Resource
    private AgencyDao agencyDao;

    @SuppressWarnings("unused")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String uri = request.getServletPath().toString();
        logger.debug("request url: {} ", uri);

        //if (uri.contains("public") || uri.contains("playway") || uri.contains("lobby") || uri.contains("user") || uri.contains("wealth") || uri.contains("msg")) {
            if (uri.contains("public")) {
            logger.debug("request url: [{}] not check", uri);
            String body = "";
            try {
                body = readHttpBody(request);
            } catch (IOException e) {
                e.printStackTrace();
            }
            request.setAttribute("json", body);
            return true;
        }

        /*if (uri.contains("api2")) {
            String body = "";
            try {
                body = readHttpBody(request);
                logger.debug("request api url: [{}] body[{}]", uri, body);
            } catch (IOException e) {
                e.printStackTrace();
            }
            request.setAttribute("json", body);

            if (uri.contains("serverlogin") || uri.contains("heartbeat")) {
                return true;
            }

            JSONObject obj = JSONObject.parseObject(body);
            int userId = obj.getInteger("serverId") == null ? 0 : obj.getInteger("serverId");
            if (userId == 0) {
                userId = obj.getInteger("userId") == null ? 0 : obj.getInteger("userId");
            }
            String token = obj.getString("token") == null ? "" : obj.getString("token");

            String tokenRadis = jedisClient.get("customertoken" + userId);
            if (token.equals(tokenRadis)) {
                // 如果用户已登录，放行。
                return true;
            } else {
                // 如果用户信息异常，返回用户登录异常信息。
                logger.debug("request api2 :{} [{}] -- [{}] not pass", "customertoken" + userId, token, tokenRadis);
                response.sendRedirect("/qiuqiudazuozhan_server/hall/public/interceptor");
                return false;
            }
        } */
        else if (uri.contains("api")) {
            String body = "";
            try {
                body = readHttpBody(request);
            } catch (IOException e) {
                logger.debug("request api url: [{}] body[{}]", uri, body);
                e.printStackTrace();
            }
            request.setAttribute("json", body);
            JSONObject obj = JSONObject.parseObject(body);
            int userId = obj.getInteger("userId") == null ? obj.getInteger("srcId") : obj.getInteger("userId");
            String token = obj.getString("token") == null ? "" : obj.getString("token");
            String tokenRadis = jedisClient.get(TOKEN + userId);
            if (token.equals(tokenRadis)) {
                // 如果用户已登录，放行。
                return true;
            } else {
                // 如果用户信息异常，返回用户登录异常信息。
                logger.debug("request api:{} [{}] -- [{}] not pass", TOKEN + userId, token, tokenRadis);
                response.sendRedirect("/qiuqiudazuozhan_server/hall/public/interceptor");
                return false;
            }
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // handle执行之后，返回ModelAndView之前。

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // 返回ModelAndView之后。
        // 可以在此处理异常

    }

    /**
     * 解析json
     *
     * @param request
     * @return
     * @throws IOException
     */
    private String readHttpBody(HttpServletRequest request) throws IOException {
        // 读取input流

        BufferedReader br = new BufferedReader(
                new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
        StringBuffer sb = new StringBuffer("");
        String temp;
        while ((temp = br.readLine()) != null) {
            sb.append(temp);
        }
        br.close();
        return sb.toString();

        /*
         * ServletRequest requestWrapper = new
         * BodyReaderHttpServletRequestWrapper(request); String body =
         * HttpHelper.getBodyString(requestWrapper); return body;
         */
    }

}
